var util = require('../../../utils/util.js');
var api = require('../../../config/api.js');
var encryption = require('../../../utils/encryption.js');
var app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    wallet: {
      id: 0,
      type: 1,
      modifyReason: '',
      recordSn: '',
      modifyAmount: '',
      modifyIntegral: 0,
      modifyResource: '',
      modifyTime: '',
      actualPayment: '',
      payType: 1,
      payId: '',
      payTime: '',
      disabled: false,
      dis: true,
      formId: null
    }
    // password:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    wx.showNavigationBarLoading() //在标题栏中显示加载
    this.payWallet
    wx.hideNavigationBarLoading() //完成停止加载
    wx.stopPullDownRefresh() //停止下拉刷新
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },

  submitInfo: function (e) {
    util.request(api.FormidCreate, { formId: e.detail.formId })
  },

  cancelPayWallet: function() {
    wx.navigateBack();
  },
  bindinputModifyAmount: function(event) {
    let wallet = this.data.wallet;
    wallet.modifyAmount = event.detail.value;
    this.setData({
      wallet: wallet
    });
  },
  bindinputPassword: function(event) {
    var password = event.detail.value;
    this.setData({
      password: password
    });
  },
  payWallet: function() {
    let that = this;
    var wallet = that.data.wallet;
    let modifyAmount  =  wallet.modifyAmount
    if (modifyAmount === "0" || modifyAmount ==="") {
      wx.showModal({
        title: '错误',
        content: "请填写充值金额!",
      });
      return ;
    }
    this.setData({
      disabled: !this.data.disabled,
      dis: false,
    });
    wallet.recordSn = this.createRecordSn();

    util.request(api.WalletPayWallet, {
      id: wallet.id,
      userId:  wallet.userId,
      type: 1,
      modifyReason: encryption.encrypt(wallet.modifyReason),
      recordSn: encryption.encrypt(wallet.recordSn),
      modifyAmount: encryption.encrypt(wallet.modifyAmount),
      modifyIntegral: 0,
      modifyResource: encryption.encrypt(wallet.modifyResource),
      modifyTime: wallet.modifyTime,
      actualPayment: encryption.encrypt(wallet.actualPayment),
      payType: 2,
      payId: wallet.payId,
      payTime: wallet.payTime

    }, 'POST').then(function(res) {
      if (res.errno === -1) {
        wx.showModal({
          title: '错误',
          content: "请求超时，请重新操作!",
          success: function (res) {
            wx.navigateBack(2);
          },
        });
      }
      if (res.errno === 0) {
        // console.log(res);
        wx.requestPayment({
          'appId': res.data.appId,
          'timeStamp': res.data.timeStamp,
          'nonceStr': res.data.nonceStr,
          'package': res.data.packageValue,
          'signType': res.data.signType,
          'paySign': res.data.paySign,
          'success': function(paymentRes) {
            // console.log(paymentRes)
            util.request(api.WalletPayNotify,{
              userId: that.data.wallet.userId,
              recordSn: that.data.wallet.recordSn
            }).then(function(res) {
              console.log("支付成功")
              console.log(res);
              if (res.data.orderStatus === 'SUCCESS') {

                wx.showModal({
                  title: '提示',
                  content: "充值成功",
                  success: function (res) {
                    wx.navigateBack(2);
                  },
                  showCancel: false
                });
                // wx.navigateBack(2);
                // wx.showToast({
                //   title: '充值成功',
                //   icon: 'success',
                //   duration: 1500
                // })
              }
            });
          },
          'fail': function(error) {
            console.log("支付错误❌")
            console.log(error)
            wx.navigateBack(2);
            wx.showToast({
              title: '取消支付',
              icon: 'none',
              duration: 1500
            })
          }
        })
      }
    });
  },
  //检查支付状态
  checkChargeStatus: function(recordSn) {
    util.request(api.WalletCheckchargestatus, {
      recordSn: recordSn
    }).then(function(res) {
      if (res.errno === 0) {
        console.log("WalletCheckchargestatus")
        console.log(res)
        wx.navigateBack();

      }
    });
  },

  //创建订单号
  createRecordSn: function() {
    var date = new Date()
    var Y = date.getFullYear()
    var M = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
    var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
    var h = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
    var m = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
    var s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
    var ss = date.getMilliseconds()
    if (ss < 10) {
      ss = '00' + ss
    } else if (ss < 100) {
      ss = '0' + ss
    }
    var result = Y.toString() + M.toString() + D.toString() + h.toString() + m.toString() + s.toString() + ss.toString();
    // result = result.replace(/\s*/g, "");
    console.log("result = " + result)
    return result
  }
})